<template>
  <div ref="reportComponent">
  <div class="form-container" >
    <!-- 顶部标题和描述 -->
    <h1>Achenbach儿童行为量表评估报告</h1>
    <!-- 第一部分，个人信息 -->
    <div>
      <h3 class="center-text"></h3>
      <el-form :model="res" label-width="120px" class="demo-form">
        <!-- 儿童姓名和性别 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="儿童姓名：" label-width="100px">
              <span>{{ res.first.childName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别：" label-width="100px">
              <span>{{ res.first.gender === 1 ? '男' : '女' }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 年龄和出生日期 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="年龄：" label-width="100px">
              <span>{{ res.first.age }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生日期：" label-width="100px">
              <span>{{ res.first.birth.year }}</span>
              年
              <span>{{ res.first.birth.month }}</span>
              月
              <span>{{ res.first.birth.day }}</span>
              日
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 填表者和填表日期 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="填表者：" label-width="100px">
              <span v-if="res.first.writer === 1">父亲</span>
              <span v-if="res.first.writer === 2">母亲</span>
              <span v-if="res.first.writer === 3">其他监护人</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="填表日期：" label-width="100px">
              <span>{{ res.first.complete.year }}</span>
              年
              <span>{{ res.first.complete.month }}</span>
              月
              <span>{{ res.first.complete.day }}</span>
              日
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 门诊号和住院号 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="门诊号：" label-width="100px">
              <span>{{ res.first.patientNumber }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="住院号：" label-width="100px">
              <span>{{ res.first.admissionNumber }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 就诊卡号 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="就诊卡号：" label-width="100px">
              <span>{{ res.first.cardNumber }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 第二部分 -->
    <div v-if="res.first.age >=6 && res.first.age <=16">
      <h3 class="center-text">社交能力</h3>
      <el-table :data="res.data_2" style="width: 840px">
        <el-table-column label="活动能力">
          <el-table-column prop="value1" label="得分" width="140"></el-table-column>
          <el-table-column prop="res1" label="评估结果" width="140"></el-table-column>
        </el-table-column>

        <el-table-column label="社交情况">
          <el-table-column prop="value2" label="得分" width="140"></el-table-column>
          <el-table-column prop="res2" label="评估结果" width="140"></el-table-column>
        </el-table-column>

        <el-table-column label="学校情况">
          <el-table-column prop="value3" label="得分" width="140"></el-table-column>
          <el-table-column prop="res3" label="评估结果" width="140"></el-table-column>
        </el-table-column>
      </el-table>
    </div>

    <!-- 第三部分 -->
    <div>
      <h3 class="center-text">行为问题</h3>
      <!-- 动态渲染表格 -->
      <el-table :data="res.data_3" style="width: 900px">
        <el-table-column prop="name" label="因子名称" width="150"></el-table-column>
        <el-table-column prop="value" label="得分" width="150"></el-table-column>
        <el-table-column prop="res" label="评估结果" width="150"></el-table-column>
      </el-table>
    </div>
  </div>
<!--    <div class="dialog-footer">-->
<!--      <el-button size="small" type="primary" @click="onExport"  id="onExport">-->
<!--        导出-->
<!--      </el-button>-->
<!--    </div>-->
  </div>


</template>

<script>
import axios from 'axios';
import {getResultByScaleScreenId, listResult} from "@/api/dcp/result";
import html2canvas from 'html2canvas';


export default {
  name: "ResultForm",
  data() {
    return {
      loading: false,
      res: {
        first: {
          childName: '',
          gender: null,
          age: null,
          birth: { year: '', month: '', day: '' },
          complete: { year: '', month: '', day: '' },
          // 其他必要字段...
        },
        data_2: [],
        data_3: []
      },
      scaleScreenId: null,
      isDataReady: false,
      isRendered: false,
    }
  },updated() {
    if (!this.isRendered) {
      this.isRendered = true;
      this.$emit('rendered');
    }
  },
  async created() {
    try {
      await this.loadData(); // 将原有逻辑封装为loadData方法
      this.isDataReady = true;
      this.$emit('data-ready'); // 通知父组件
    } catch (error) {
      console.error('数据加载失败:', error);
    }
  },methods:{
    async checkTableRendered() {
      await this.$nextTick();
      const tables = this.$el.querySelectorAll('.el-table');
      if (tables.length === 0) return false;

      const isRendered = Array.from(tables).every(table => {
        return table.querySelectorAll('.el-table__row').length > 0;
      });

      // 如果检测到已渲染但尚未触发事件，则触发
      if (isRendered && !this.isRendered) {
        this.isRendered = true;
        this.$emit('rendered');
      }

      return isRendered;
    },
    async loadData(scaleScreenId = null) {
      this.loading = true;
      try {
        this.scaleScreenId = scaleScreenId || this.$route.query.row?.scaleScreenId;

        if (!this.scaleScreenId) {
          throw new Error('缺少scaleScreenId');
        }

        const response = await listResult({ scaleScreenId: this.scaleScreenId });
        this.res = JSON.parse(response.rows[0].resultContent);
        this.$emit('data-ready');
      } catch (error) {
        console.error('加载数据失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },
    getUrlBase64(url, kh) {
      return new Promise((resolve) => {
        let canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        const img = new Image();
        img.crossOrigin = 'Anonymous'; // 允许跨域
        img.src = url;
        img.onload = () => {
          // eslint-disable-next-line prefer-destructuring
          canvas.height = kh[1];
          // eslint-disable-next-line prefer-destructuring
          canvas.width = kh[0];
          ctx.drawImage(img, 0, 0, kh[0], kh[1]);
          const dataURL = canvas.toDataURL('image/png');
          canvas = null;
          resolve(dataURL);
        };
      });
    },
    download(imgUrl, kh){
      this.getUrlBase64(imgUrl, kh).then((base64) => {
        const link = document.createElement('a');
        link.href = base64;
        link.download = `${this.currentRobot.nickname}名片.png`;
        link.click();
      });
    },


  }
}
</script>

<style scoped>
.form-container {
  margin: 20px auto;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

</style>
